
//  SettingViewController.m
//  one_mile_01
//
//  Created by 王雅蓉 on 15/8/21.
//  Copyright (c) 2015年 王雅蓉. All rights reserved.
//

#import "SettingViewController.h"
#import "EditUserInfoViewController.h"
#import "LoginViewController.h"
#import "LovingTutorsViewController.h"
#import "SheetMenuView.h"

@interface SettingViewController ()<UIAlertViewDelegate, SheetMenuDelegate>

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = BACKGROUND_ASSISTANT_COLOR;
    self.navigationController.navigationBar.hidden = YES;
    
    UIView *navigationV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, NAVIGATIONHEIGHT)];
    navigationV.backgroundColor = BACKGROUND_MAIN_COLOR;
    [self.view addSubview:navigationV];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH / 2.0 - NAVIGATION_TITLE_WIDTH / 2.0, NAVIGATIONHEIGHT - NAVIGATION_TITLE_HEIGHT - 5, NAVIGATION_TITLE_WIDTH, NAVIGATION_TITLE_HEIGHT)];
    titleLabel.text = @"我";
    titleLabel.font = [UIFont systemFontOfSize:20.0f];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:titleLabel];
    
    self.settingTableView = [[UITableView alloc] init];
    if (iPhone6) {
        
        self.settingTableView.frame = CGRectMake(0, NAVIGATIONHEIGHT, self.view.frame.size.width,86 + 45 * 6 + 15 + 22 + 19);
    }else{
        
        self.settingTableView.frame = CGRectMake(0, NAVIGATIONHEIGHT, self.view.frame.size.width,   15 * HEIGHT / 667 + 86 * HEIGHT / 667 + 45 * HEIGHT / 667 * 6 + 22 * HEIGHT / 667 + 19 * HEIGHT / 667);
    }
    self.settingTableView.backgroundColor = RGBACOLOR(240, 239, 245, 1.0);
    self.settingTableView.delegate = self;
    self.settingTableView.dataSource = self;
    self.settingTableView.scrollEnabled = NO;
    
    [[UITableViewHeaderFooterView appearance] setTintColor:RGBACOLOR(240, 239, 245, 1.0)];
    [self.view addSubview:self.settingTableView];
    
    UIButton *backLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backLoginButton.backgroundColor = [UIColor whiteColor];
    [backLoginButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [backLoginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    if (iPhone6) {
        
        backLoginButton.frame = CGRectMake(0, self.settingTableView.frame.origin.y + self.settingTableView.frame.size.height + 19, WIDTH, 45);
        backLoginButton.titleLabel.font = [UIFont systemFontOfSize:16];
    }else{
        
        backLoginButton.frame = CGRectMake(0, self.settingTableView.frame.origin.y + self.settingTableView.frame.size.height + 19 * HEIGHT / 667, WIDTH, 45 * HEIGHT / 667);
        backLoginButton.titleLabel.font = [UIFont systemFontOfSize:16 * HEIGHT / 667];
    }
    [backLoginButton addTarget:self action:@selector(backLoginButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backLoginButton];


    }

#pragma mark -- tapGestureAction
//-(void)editUserInfoTap:(UITapGestureRecognizer *)tap
//{
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
//
//        EditUserInfoViewController *editUsersVC = [[EditUserInfoViewController alloc] init];
//        editUsersVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//
//        [self presentViewController:editUsersVC animated:YES completion:^{
//
//
//        }];
//    } else {
//
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录，请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
//        [self.view addSubview:alert];
//
//        [alert show];
//
//        alert.delegate = self;
//    }
//}


#pragma mark -- alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([alertView.message isEqualToString:@"您还未登录，请先登录"] || [alertView.message     isEqualToString:@"您还未登录哦，亲。。。"]) {
    
        if (buttonIndex == 1) {
        
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            loginVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            
            [self presentViewController:loginVC animated:YES completion:^{
                
            }];
        }
    }
    if ([alertView.message isEqualToString:@"是否清除缓存数据"]) {
    
        [[SDImageCache sharedImageCache] cleanDisk];
    
        if (buttonIndex == 1) {
        
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
                NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                
                for (NSString *p in files) {
                    
                    NSError *error;
                    NSString *path = [cachPath stringByAppendingPathComponent:p];
                    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                    
                        [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                    }
                }
                [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
            });
        }
    }
}
//清除缓存成功
-(void)clearCacheSuccess
{
    [self showAlert:@"清除成功"];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        if (iPhone6)    return 15;
        else    return HEIGHT * 15 / 667.0;
    } else if (section == 1) {
        if (iPhone6)    return 23;
        else    return HEIGHT * 23 / 667.0;
    } else {
        if (iPhone6)    return 19;
        else    return HEIGHT * 19 / 667.0;
    }
}

#pragma mark -- tableviewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
    
        return 1;
    } else if (section == 1) {
    
        return 5;
    } else {
    
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        if (iPhone6)    return 86;
        else    return HEIGHT * 86 / 667;
        
    } else {
        if (iPhone6)    return 45;
        else    return HEIGHT * 45 / 667;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"mySettingCell";
    settingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[settingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//取消cell点击效果
        cell.backgroundColor = [UIColor whiteColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
        if (iPhone6) {
        
            cell.iconImageview.frame = CGRectMake(13,13, 61, 61);
            cell.iconImageview.layer.cornerRadius = 30;
        } else {
        
            cell.iconImageview.frame = CGRectMake(HEIGHT * 13 / 667, HEIGHT * 13 / 667, HEIGHT * 61 / 667, HEIGHT * 61 / 667);
            cell.iconImageview.layer.cornerRadius = HEIGHT * 61 / 667 / 2;
        }
        cell.iconImageview.layer.masksToBounds = YES;
    
        cell.nameLabel.frame = CGRectMake(cell.iconImageview.frame.origin.x + cell.iconImageview.frame.size.width + 20 ,20, 200, 30);
        if (iPhone6) {
            
            cell.nameLabel.font = [UIFont systemFontOfSize:19];
        } else {
            cell.nameLabel.font = [UIFont systemFontOfSize:HEIGHT * 19 / 667];
        }
        [self.view addSubview:self.nameLabel];
        
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            [cell.iconImageview sd_setImageWithURL:[NSURL URLWithString:[[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"] objectForKey:@"iconUrl"]] placeholderImage:[UIImage imageNamed:@"placeholders.png"]];
            cell.nameLabel.text = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"] objectForKey:@"nickName"];
        } else {
            cell.iconImageview.image = [UIImage imageNamed:@"placeholders.png"];
            cell.nameLabel.text = @"未登录";
        }
    }
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        cell.nameLabel.text = @"成为导师";
        cell.iconImageview.image = [UIImage imageNamed:@"manage_tobeTutor@2x.png"];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        cell.nameLabel.text = @"你的导师";
        cell.iconImageview.image = [UIImage imageNamed:@"manage_lovingtutor@2x.png"];
    } else if (indexPath.section == 1 && indexPath.row == 2) {
        cell.nameLabel.text = @"导师主页";
        cell.iconImageview.image = [UIImage imageNamed:@"manage_tutorhome@2x.png"];
    } else if (indexPath.section == 1 && indexPath.row == 3) {
        cell.nameLabel.text = @"查看评价";
        cell.iconImageview.image = [UIImage imageNamed:@"manage_comments@2x.png"];
    } else if (indexPath.section == 1 && indexPath.row == 4) {
        cell.nameLabel.text = @"账户安全";
        cell.iconImageview.image = [UIImage imageNamed:@"manage_accountSecurity@2x.png"];
    }
    
    if(indexPath.section == 2 && indexPath.row == 0){
        cell.nameLabel.text = @"设置";
        cell.iconImageview.image = [UIImage imageNamed:@"manage_setting@2x.png"];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            
            EditUserInfoViewController *editUsersVC = [[EditUserInfoViewController alloc] init];
            editUsersVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self.navigationController pushViewController:editUsersVC animated:YES];
            
        } else {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录，请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
            [self.view addSubview:alert];
            
            [alert show];
            
            alert.delegate = self;
        }
        
    }
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {

        
        if (((NSString *)[[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"] objectForKey:@"teacherID"]).length == 0) {
            
            applyTutorViewController *applyTutorVC = [[applyTutorViewController alloc]init];
            [self.navigationController pushViewController:applyTutorVC animated:YES];
        } else {
            
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您已经是导师了哦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertV show];
        }
        }else{
        
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录哦，亲。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录" ,nil];
            [self.view addSubview:alert];
            
            [alert show];

        }
        
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录哦，亲。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录" ,nil];
            [self.view addSubview:alert];
            
            [alert show];
        } else {
            
            LovingTutorsViewController *loveTutorVC = [[LovingTutorsViewController alloc] init];
            [self.navigationController pushViewController:loveTutorVC animated:YES];
        }
    } else if (indexPath.section == 1 && indexPath.row == 2){
        
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录哦，亲。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
            [self.view addSubview:alert];
            
            [alert show];
        } else {
            
            NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
            
            for (NSString *key in dic.allKeys) {
                
                if ([key isEqualToString:@"teacherID"]) {
                    
                    [TagForClient shareTagDataHandle].isTeacher = YES;
                    break;
                }
                else{
                    
                    [TagForClient shareTagDataHandle].isTeacher = NO;
                }
            }
            
            if ([TagForClient shareTagDataHandle].isTeacher) {
                
                EditTutorInfoViewController *editTutorVC = [[EditTutorInfoViewController alloc] init];
                NSString *tid = [dic objectForKey:@"teacherID"];
                editTutorVC.toDetialID = tid;
                
                [self.navigationController pushViewController:editTutorVC animated:YES];
            } else {
                
                UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"很遗憾，您不是导师，没有权限。" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alertV show];
            }
        }
    } else if (indexPath.section == 1 && indexPath.row == 4){
        
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录哦，亲。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
            
            [alert show];
        } else {
            AccountSecurityViewController *accountSecurityVC = [[AccountSecurityViewController alloc]init];
            [self.navigationController pushViewController:accountSecurityVC animated:YES];
        }
    } else if(indexPath.section == 1 && indexPath.row == 3) {
        
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录哦，亲。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
            
            [alert show];
        } else {
            watchCommentViewController *accountSecurityVC = [[watchCommentViewController alloc]init];
            [self.navigationController pushViewController:accountSecurityVC animated:YES];
        }
    }
    
    if (indexPath.section == 2 && indexPath.row == 0) {
        
        settingDetailViewController *settingDetailVC = [[settingDetailViewController alloc]init];
        [self.navigationController pushViewController:settingDetailVC animated:YES];
    }
}

#pragma mark -- viewWillAppear
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    self.navigationController.navigationBar.alpha = 0;
    self.tabBarController.tabBar.hidden = NO;
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:[[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"] objectForKey:@"iconUrl"]] placeholderImage:[UIImage imageNamed:@"placeholders.png"]];
        self.nameLabel.text = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"] objectForKey:@"nickName"];
        [self.settingTableView reloadData];
    } else {
        
        self.nameLabel.text = @"未登录";
        self.imageView.image = [UIImage imageNamed:@"placeholders.png"];
        [self.settingTableView reloadData];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.alpha = 1;
    //    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    self.tabBarController.tabBar.hidden = NO;
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:[[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"] objectForKey:@"iconUrl"]] placeholderImage:[UIImage imageNamed:@"placeholders.png"]];
        self.nameLabel.text = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"] objectForKey:@"nickName"];
        
    } else {
        
        self.nameLabel.text = @"未登录";
        self.imageView.image = [UIImage imageNamed:@"placeholders.png"];
    }
}

#pragma mark -- 警示框回弹自动
-(void)showAlert:(NSString *)message{//时间
    
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.0f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}

- (void)timerFireMethod:(NSTimer *)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView * )[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert = NULL;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- sheetMenuDelegate
-(void)backLoginButtonAction{
    
    SheetMenuView *sheetV = [[SheetMenuView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    sheetV.myDelegate = self;
    [sheetV showSheetMenuView:nil];
}

-(void)didSelectMenuIndex:(NSIndexPath *)index
{
    if (index.section == 0) {
        if (index.row == 1) {
            
            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"isLogin"];
            [self.settingTableView reloadData];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
